<?php
/**
 * 上传文件
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/9
 * Time: 16:19
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use app\common\model\Attachment as AttachmentModel;
use base\OssApi;
use OSS\Core\OssException;
use think\Config;
use think\Image;

class Upload extends AdminBase
{
    public function uploadImg()
    {
        $file = $this->request->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {

            //保存到数据库
            $currentTime = time();

            $attachementMode               = new AttachmentModel();
            $attachementMode->tid          = 0;
            $attachementMode->uid          = $this->currentUser->id;
            $attachementMode->type         = 'upload';
            $attachementMode->filename     = $info->getFilename();
            $attachementMode->filesize     = $info->getSize();
            $attachementMode->attachment   = $info->getSaveName();
            $attachementMode->description  = $info->getSaveName();
            $attachementMode->isimage      = $info->isFile();
            $attachementMode->thumb        = 0;
            $attachementMode->width        = 0;
            $attachementMode->height       = 0;
            $attachementMode->updated_time = $currentTime;
            $attachementMode->created_time = $currentTime;

            $attachementMode->save();

            //上传到OSS
            $ossUpload = Config::has('OSS_UPLOAD') ? Config::get('OSS_UPLOAD') : false;
            if ($ossUpload) {
                try {
                    $fileName  = 'uploads/' . $info->getSaveName();
                    $ossClient = OssApi::getInstance();
                    $bucket    = OssApi::getBucketName();
                    $ossClient->uploadFile($bucket, $fileName, $info->getPathname());
                } catch (OssException $e) {
                    return json($e->getMessage(), -1);
                }
            }

            return json($attachementMode);

        } else {
            // 上传失败获取错误信息
            return json([$file->getError(), -1]);
        }
    }
}